//
//  TrafficMonitor.swift
//  AICleaner
//
//  Created by firefly on 2025/1/27.
//

import SwiftUI
import Network
import NetworkExtension

/// 流量监控
class TrafficMonitor: NSObject, URLSessionTaskDelegate {
    static let shared = TrafficMonitor()
    private var sentBytes: Int64 = 0
    private var receivedBytes: Int64 = 0
    private var networkStatus: String = "Unknown"
    private var timer: Timer?
    
    private override init() {}

    private func startMonitoring() {
            // Start network status monitoring
            let monitor = NWPathMonitor()
            monitor.pathUpdateHandler = { path in
                DispatchQueue.main.async {
                    if path.status == .satisfied {
                        if path.usesInterfaceType(.wifi) {
                            self.networkStatus = "Wi-Fi"
                        } else if path.usesInterfaceType(.cellular) {
                            self.networkStatus = "Cellular"
                        } else {
                            self.networkStatus = "Other"
                        }
                    } else {
                        self.networkStatus = "No Connection"
                    }
                }
            }
            monitor.start(queue: DispatchQueue.global(qos: .background))

            // Start traffic monitoring
            timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
                self.updateTrafficStats()
            }
        }

        private func stopMonitoring() {
            timer?.invalidate()
            timer = nil
        }

        private func updateTrafficStats() {
            if let stats = getNetworkTrafficStats() {
                sentBytes = stats.sent
                receivedBytes = stats.received
            }
        }

        private func getNetworkTrafficStats() -> (sent: Int64, received: Int64)? {
            // Use NetworkExtension to get traffic stats
//            if let provider = NEProvider.shared() as? NEFilterDataProvider {
//                let stats = provider.currentStatistics()
//                return (sent: stats.txBytes, received: stats.rxBytes)
//            }
            return nil
        }

        private func formatBytes(_ bytes: Int64) -> String {
            let formatter = ByteCountFormatter()
            formatter.allowedUnits = [.useKB, .useMB, .useGB]
            formatter.countStyle = .binary
            return formatter.string(fromByteCount: bytes)
        }
}
